<?php

namespace App\Imports;

use App\Models\Talent;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class TalentImport implements ToCollection
{
    public $project_id;

    public function __construct($project_id)
    {
        $this->project_id = $project_id;
    }

    /**
     * @param Collection $rows
     */
    public function collection(Collection $rows)
    {
        foreach ($rows as $key => $row) {
            if ($key > 0) {
                $talent = $this->checkExists($row);
                if ($talent) {
                    // 更新
                    $talent->update([
                        'name' => $row[0],
                        'recommend' => $row[1],
                        'sex' => $row[2] === '男' ? 0: 1,
                        'birthday' => gmdate('Y-m-d', \PHPExcel_Shared_Date::ExcelToPHP($row[3])),
                        'education' => $row[4],
                        'university' => $row[5],
                        'profession' => $row[6],
                        'year' => $row[7],
                        'recently_company' => $row[8],
                        'recently_job' => $row[9],
                        'annual_income' => $row[10],
                        'expected_salary' => $row[11],
                        'project_id' => $this->project_id,
                    ]);
                } else {
                    Talent::create([
                        'name' => $row[0],
                        'recommend' => $row[1],
                        'sex' => $row[2] === '男' ? 0: 1,
                        'birthday' => gmdate('Y-m-d', \PHPExcel_Shared_Date::ExcelToPHP($row[3])),
                        'education' => $row[4],
                        'university' => $row[5],
                        'profession' => $row[6],
                        'year' => $row[7],
                        'recently_company' => $row[8],
                        'recently_job' => $row[9],
                        'annual_income' => $row[10],
                        'expected_salary' => $row[11],
                        'project_id' => $this->project_id,
                    ]);
                }
            }
        }
    }

    private function checkExists($row)
    {
        $talent = Talent::where('name', $row[0])
            ->where('sex', $row[2] === '男' ? 0: 1)
            ->where('birthday', gmdate('Y-m-d', \PHPExcel_Shared_Date::ExcelToPHP($row[3])))
            ->first();

        return $talent;
    }
}
